package net.sudot.chess.business.support;

import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy;

import java.util.Locale;

/**
 * 物理命名策略，用于转换“逻辑名称”(隐式或显式)的表或列成一个物理名称
 *
 * @author tangjialin on 2018-12-14.
 */
public class PhysicalNamingStrategy extends SpringPhysicalNamingStrategy {
    public static final String TABLE_PREFIX = "chess_";

    @Override
    public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment jdbcEnvironment) {
        name = new Identifier(TABLE_PREFIX + name.getText(), name.isQuoted());
        return super.toPhysicalTableName(name, jdbcEnvironment);
    }

    /**
     * 重写父类方法，额外处理数据库关键字
     *
     * @param name            标识符的名称
     * @param quoted          是否为关键字
     * @param jdbcEnvironment JDBC环境
     * @return 新的标识符实例
     */
    @Override
    protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) {
        if (isCaseInsensitive(jdbcEnvironment)) {
            name = name.toLowerCase(Locale.ROOT);
        }
        // 检查是否为数据库关键字
        if (quoted || jdbcEnvironment.getIdentifierHelper().isReservedWord(name)) {
            quoted = true;
        }
        return new Identifier(name, quoted);
    }
}
